package com.song.tools.songtest.config;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;

/**
 * 分布式Snowflake
 *
 * @author song tools
 * @since 2024-07-15
 */
public class DistributedSnowflake {

    private static final long WORKER_ID_BITS = 5L;
    private static final long DATACENTER_ID_BITS = 5L;
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS);

    private final Snowflake snowflake;

    public DistributedSnowflake(long workerId, long datacenterId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", MAX_WORKER_ID));
        }
        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", MAX_DATACENTER_ID));
        }
        snowflake = IdUtil.getSnowflake(workerId, datacenterId);
    }

    public synchronized long nextId() {
        return snowflake.nextId();
    }

    public synchronized String nextIdStr() {
        return snowflake.nextIdStr();
    }
}
